﻿using AntdUI;
using Super.Admin.Global;
using Super.Admin.IServices;
using Super.Admin.Mappers;
using Super.Admin.Models.Department;
using Super.Admin.Models.Permission;
using Super.Admin.Models.Role;
using Super.Admin.Models.User;
using Super.Admin.Services;
using Super.Admin.Utils;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Views.Base;
using Super.Admin.Views.Main;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Super.Admin.Views.Page
{
    public partial class RoleManagementView : BaseUserControl
    {
        private readonly IUserOperateLogService _userOperateLogService;
        private readonly IRoleService _roleService;
        private readonly IPermissionService _permissionService;
        private List<PermissionBaseModel> _permissionModels = new List<PermissionBaseModel>();

        private bool _isLoad = false;
        private List<CellButton> _cellButtons = new List<CellButton>();

        public RoleManagementView(IUserOperateLogService userOperateLogService, IRoleService roleService, IPermissionService permissionService)
        {
            InitializeComponent();
            InitializeAuthPermissionList();
            this.Load += UserManagementView_Load;
            _userOperateLogService = userOperateLogService;
            _permissionService = permissionService;
            _roleService = roleService;
        }

        private void UserManagementView_Load(object? sender, EventArgs e)
        {
            _isLoad = true;
            InitializeControls();

            TableRoleModel.Columns = new AntdUI.ColumnCollection
            {
                new AntdUI.ColumnCheck("Check"),
                new AntdUI.Column("Index","序号",ColumnAlign.Center).SetFixed().SetWidth("80"),
                new AntdUI.Column("Id","角色ID",ColumnAlign.Center).SetFixed().SetWidth("80").SetSortOrder(true),
                new AntdUI.Column("Name","角色名称",ColumnAlign.Center).SetFixed().SetWidth("200").SetSortOrder(true),
                new AntdUI.Column("IsActiveTag","角色状态", ColumnAlign.Center).SetFixed().SetWidth("100").SetSortOrder(true),
                new AntdUI.Column("Remark","备注", ColumnAlign.Center).SetFixed().SetWidth("400").SetSortOrder(true),
                new AntdUI.Column("CreateTime","创建时间", ColumnAlign.Center).SetFixed().SetWidth("220").SetSortOrder(true),
                new AntdUI.Column("UpdateTime","修改时间", ColumnAlign.Center).SetFixed().SetWidth("220").SetSortOrder(true),
                new AntdUI.Column("Operates","操作", ColumnAlign.Center).SetFixed(),
            };

            LoadPermissionList();
            _isLoad = false;
        }

        private void InitializeAuthPermissionList()
        {
            BtnCreate.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.RoleCreate);
            BtnSerach.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.RoleSearch);
            BtnBatchDelete.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.RoleBatchDelete);

            // 单元格按钮
            _cellButtons.Clear();
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.RoleUpdate))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.RoleUpdate, "编辑", TTypeMini.Primary) { });
            }
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.RoleDelete))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.RoleDelete, "删除", TTypeMini.Error) { });
            }
        }

        private void LoadPermissionList()
        {
            _permissionModels = SetPermissionList((List<PermissionBaseModel>)_permissionService.GetPermissions().ToBaseModels(), 0);
        }

        public List<PermissionBaseModel> SetPermissionList(List<PermissionBaseModel> sourceModel, int parent = 0)
        {
            List<PermissionBaseModel> permissionModels = new List<PermissionBaseModel>();
            List<PermissionBaseModel> list = sourceModel.Where(s => s.ParentId == parent).ToList();
            foreach (var l in list)
            {
                permissionModels.Add(l);
                foreach (var menu in permissionModels)
                {
                    menu.Children = GetChildren(sourceModel, menu.Id).ToArray();
                    menu.PermissionChildren = GetChildren(sourceModel, menu.Id);
                }
            }
            return permissionModels;
        }
        private List<PermissionBaseModel> GetChildren(List<PermissionBaseModel> sourceModel, int parentId)
        {
            var children = sourceModel.Where(m => m.ParentId == parentId).ToList();
            foreach (var child in children)
            {
                child.Children = GetChildren(sourceModel, child.Id).ToArray();
                child.PermissionChildren = GetChildren(sourceModel, child.Id);
            }
            return new List<PermissionBaseModel>(children);
        }

        public override void DoRefresh()
        {
            BtnSerach.PerformClick();
        }

        // 初始化 重置参数
        private void InitializeControls()
        {
            TxtRoleName.Text = "";
            TxtRoleId.Value = -1;
            TxtRermark.Text = "";
            CmbStatus.SelectedIndex = -1;
            DatePickerRange.Value = null;

            CmbStatus.Items.Clear();
            CmbStatus.Items.AddRange(new AntdUI.ISelectItem[] { new AntdUI.SelectItem("启用", 0), new AntdUI.SelectItem("停用", 1) });
            CmbStatus.SelectedIndex = -1;

            Pagination.PageSizeOptions = new int[] { 10, 20, 30, 50, 100 };
            Pagination.Current = 1;
        }

        private void PnlSearch_ExpandChanged(object sender, AntdUI.CollapseExpandEventArgs e)
        {
            GridMain.SuspendLayout();
            if (e.Expand)
            {
                GridMain.Span = "160:100%;10:100%;100%:100%";
            }
            else
            {
                GridMain.Span = "47:100%;10:100%;100%:100%";
            }
            GridMain.ResumeLayout();
        }
        private void BtnReset_Click(object sender, EventArgs e)
        {
            InitializeControls();
        }

        private void BtnCreate_Click(object sender, EventArgs e)
        {
            Drawer.Config config = new Drawer.Config(ParentForm, new RoleManagementModify(ParentForm, new RoleBaseModel { }, _permissionModels, _roleService, _userOperateLogService, "新增角色") { Width = 400 })
            {
                Align = TAlignMini.Right
            };
            config.OnClose = () =>
            {
                DoRefresh();
            };
            config.open();
        }

        private void BtnSerach_Click(object sender, EventArgs e)
        {
            try
            {
                int status = -1;
                if (CmbStatus.SelectedValue != null && CmbStatus.SelectedIndex != -1)
                {
                    status = Convert.ToInt32(CmbStatus.SelectedValue);
                }
                string startTime = "", endTime = "";
                if (DatePickerRange.Value != null)
                {
                    startTime = DatePickerRange.Value[0].ToString("yyyy-MM-dd 08:30:00");
                    endTime = DatePickerRange.Value[1].ToString("yyyy-MM-dd 08:29:59");
                }
                var roleEntities = _roleService.GetRoles(TxtRoleName.Text, (int)TxtRoleId.Value, status, TxtRermark.Text, startTime, endTime, Pagination.PageSize, Pagination.Current, out int totalCount);
                Pagination.Total = totalCount;
                var roleModels = roleEntities.ToBaseModels().ToList();
                if (roleModels.Count == 0 && totalCount != 0)
                {
                    Pagination.Current = 0;
                    return;
                }
                foreach (var role in roleModels)
                {
                    // 索引
                    role.Index = ((Pagination.Current - 1) * (int)Pagination.PageSize) + roleModels.IndexOf(role) + 1;
                    // 按钮
                    role.Operates = TableHelper.CopyCellButton(_cellButtons).ToArray();
                }
                TableRoleModel.DataSource = roleModels;
                _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"角色管理搜索", "system:role:serach");
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(ParentForm, ex.Message);
            }
        }

        private void Pagination_ValueChanged(object sender, PagePageEventArgs e)
        {
            if (_isLoad) return;
            DoRefresh();
        }

        private string Pagination_ShowTotalChanged(object sender, PagePageEventArgs e)
        {
            return $"{e.PageSize} / {e.Total}条 {e.PageTotal}页";
        }

        private void TableRoleModel_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is RoleBaseModel model)
            {
                if (e.Btn.Id == PermissionKeys.RoleDelete)
                {
                    var result = AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "是否删除", new AntdUI.Modal.TextLine[]
                    {
                        new Modal.TextLine(model.Id +"-"+ model.Name ,AntdUI.Style.Db.Primary),
                    }, AntdUI.TType.Error)
                    {
                        CancelText = "取消",
                        OkType = TTypeMini.Error,
                        OkText = "删除"
                    });
                    if (result == DialogResult.OK)
                    {
                        _roleService.DeleteRole(model.Id);
                        _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"权限管理删除：【{model.Id}-{model.Name}】", PermissionKeys.RoleDelete);
                        AntdUI.Message.success(ParentForm, "删除成功");
                        DoRefresh();
                    }
                }
                else if (e.Btn.Id == PermissionKeys.RoleUpdate)
                {
                    Drawer.Config config = new Drawer.Config(ParentForm, new RoleManagementModify(ParentForm, model, _permissionModels, _roleService, _userOperateLogService, "新增角色") { Width = 400 })
                    {
                        Align = TAlignMini.Right
                    };
                    config.OnClose = () =>
                    {
                        DoRefresh();
                    };
                    config.open();
                }
            }
        }

        private void BtnBatchDelete_Click(object sender, EventArgs e)
        {
            // 删除选中的 
            List<RoleBaseModel> models = TableRoleModel.DataSource as List<RoleBaseModel>;
            List<RoleBaseModel> selectModels = models.Where(m => m.Check).ToList();
            try
            {
                if (selectModels.Count == 0) return;
                string nameList = "";
                foreach (var name in selectModels)
                {
                    nameList += name.Name + ",";
                }
                var result = AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "是否删除", new AntdUI.Modal.TextLine[]
                {
                    new Modal.TextLine(nameList.TrimEnd(','),AntdUI.Style.Db.Primary),
                }, AntdUI.TType.Error)
                {
                    CancelText = "取消",
                    OkType = TTypeMini.Error,
                    OkText = "删除"
                });
                if (result == DialogResult.OK)
                {
                    foreach (var model in selectModels)
                    {
                        _roleService.DeleteRole(model.Id);
                    }
                    _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"角色管理批量删除：【{nameList.TrimEnd(',')}】", "system:role:batchdelete");
                    AntdUI.Message.success(ParentForm, "删除成功");
                    DoRefresh();
                }
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(ParentForm, "删除失败：" + ex.Message);
            }
        }
    }
}
